<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/

class event_db extends Model{
	public $pk = 'event_log_id';
	public $table = 'ptx_event_log';

	var $linker = array(
			'everule'=>array(
					'type' => 'hasone',
					'map' => 'everule',
					'mapkey' => 'event_id',
					'ftable' => 'ptx_event',
					'fkey' => 'event_id',
					'enabled' => false
			)
	);


	public function getEventByUserAndRule($uid,$rid){
		if($log = $this->find(array('user_id'=>$uid,'event_id'=>$rid))){
			return $log;
		}else{
			$logid = $this->create(array('event_id'=>$rid,'user_id'=>$uid,'starttime'=>TIMESTAMP,'dateline'=>0));
			return $this->findBy('event_log_id', $logid);
		}
	}

	public function getLastestEventByUser($uid){
		$this->enableLinker('everule');
		return $this->findJoin(array('user_id'=>$uid,'is_read'=>'0')," ptx_event_log.dateline DESC ");
	}

	public function clean_log($uid,$starttime){
		$this->update(" user_id='{$user_id}' AND dateline<'{$starttime}' ", array('is_read'=>'1'));
	}

	public function renewEventByUserAndRule($uid,$rid,$starttime){
		if($log = $this->getEventByUserAndRule($uid, $rid)){
			$data['starttime']=$starttime;
			$data['cyclenum']=1;
			$data['ext_credits_1']=0;
			$data['ext_credits_2']=0;
			$data['ext_credits_3']=0;
			$data['is_read']=0;
			$this->update(array('event_log_id'=>$log['event_log_id']), $data);
		}else{
			$this->create(array('event_id'=>$rid,'user_id'=>$uid,'starttime'=>TIMESTAMP,'dateline'=>0));
		}
	}

}